package com.android.jingweiapp.activity;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.VideoView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.GetContentAndPathXMLPhase;
import com.android.jingweiapp.XMLPhase.OnlineJudgeContentXMLPhase;
import com.android.jingweiapp.XMLPhase.SpecialContentXMLPhase;
import com.android.jingweiapp.XMLPhase.TopicContentXMLPhase;
import com.android.jingweiapp.adapter.ImageAdapter;
import com.android.jingweiapp.bean.NewsBean;
import com.android.jingweiapp.bean.OnlineJudgeBean;
import com.android.jingweiapp.bean.PicBean;
import com.android.jingweiapp.bean.PicNewsBean;
import com.android.jingweiapp.bean.TopicSecondBean;
import com.android.jingweiapp.util.CommonUtil;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 图片新闻
 */
public class NewsDetailPicActivity extends AppCompatActivity {

    //轮播图图片数量
    private final static int IMAGE_COUNT = 6;
    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.tv_detail_title)
    TextView tvDetailTitle;
    @Bind(R.id.tv_detail_time)
    TextView tvDetailTime;
    @Bind(R.id.tv_detail_from)
    TextView tvDetailFrom;
    @Bind(R.id.pic_viewpager)
    ViewPager viewpager;
    @Bind(R.id.tv_detail_content)
    WebView tvDetailContent;
    @Bind(R.id.tv_picDesc)
    TextView tvPicDesc;
    private ProgressDialog progressDialog;
    private ArrayList<SimpleDraweeView> draweeViews;
    private ImageAdapter imageAdapter;
    private int currentItem = 0;
    private String [] mPicDescs;//图片描述
    private String mPicDesc;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    viewpager.setCurrentItem(currentItem);
            }
        }
    };
    //自动轮播启用开关
    private ScheduledExecutorService scheduledExecutorService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_detail_pic);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        int type = getIntent().getIntExtra(Contacts.KEY.KEY_TYPE, 0);

        if (type == 0) {
            NewsBean newsBean = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(newsBean.getTitle());
            tvDetailFrom.setText(newsBean.getFrom());
            tvDetailTime.setText(newsBean.getTime());
            new PicNewsAsyncTask().execute(newsBean.getId());
        } else if (type == Contacts.TYPE.TOPIC_NEWS) {
            TopicSecondBean.DataEntity dataEntity = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(dataEntity.getTitle());
            tvDetailFrom.setText(dataEntity.getSource());
            tvDetailTime.setText(dataEntity.getTime());
            new TopicAsyncTask().execute(dataEntity.getId());
        } else if (type == Contacts.TYPE.SPECIAL_NEWS) {
            TopicSecondBean.DataEntity dataEntity = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(dataEntity.getTitle());
            tvDetailFrom.setText(dataEntity.getSource());
            tvDetailTime.setText(dataEntity.getTime());
            new SpecialAsyncTask().execute(dataEntity.getId());
        } else if (type == Contacts.TYPE.TOPIC_NEWS_SPECIAL) {
            NewsBean data = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(data.getTitle());
            tvDetailFrom.setText(data.getFrom());
            tvDetailTime.setText(data.getTime());
            new TopicAsyncTask().execute(data.getId());
        } else if (type == Contacts.TYPE.SPECIAL_NEWS_SPECIAL) {
            NewsBean data = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(data.getTitle());
            tvDetailFrom.setText(data.getFrom());
            tvDetailTime.setText(data.getTime());
            new SpecialAsyncTask().execute(data.getId());
        }else if(type==-1){
            PicBean picBean = getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(picBean.getTitle());
            tvDetailFrom.setText(picBean.getFrom());
            tvDetailTime.setText(picBean.getDate());
            new PicNewsAsyncTask().execute(picBean.getId());
        }else if(type==Contacts.TYPE.ONLINEJUDGE_PIC){
            //在线访谈。没有视频的在线访谈
            OnlineJudgeBean.DataEntity onlineJudgeBean=getIntent().getParcelableExtra(Contacts.KEY.KEY_OBJECT);
            tvDetailTitle.setText(onlineJudgeBean.getTitle());
            tvDetailFrom.setText(onlineJudgeBean.getPerson());
            tvDetailTime.setText(onlineJudgeBean.getTime());
            new OnLineJudgeAsyncTask().execute(onlineJudgeBean.getId());
        }
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        draweeViews = new ArrayList<>();
        imageAdapter = new ImageAdapter(draweeViews);
        viewpager.setAdapter(imageAdapter);
        viewpager.addOnPageChangeListener(new MyPageChangeListener());
    }


    public void dealData(String content) {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(content)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (content.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        Gson gson = new Gson();
        PicNewsBean picNewsBean = gson.fromJson(content, PicNewsBean.class);
        tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL,picNewsBean.getData().get(0).getContent(),"text/html","UTF-8",null);
        if(TextUtils.isEmpty(picNewsBean.getData().get(0).getContent()) || "&nbsp;".equals(picNewsBean.getData().get(0).getContent())){
            tvDetailContent.setVisibility(View.GONE);
        }
        else{
            tvDetailContent.setVisibility(View.VISIBLE);
        }
        //tvDetailContent.setText(Html.fromHtml(picNewsBean.getData().get(0).getContent()));
        mPicDesc=picNewsBean.getData().get(0).getPicDesc();
        if(TextUtils.isEmpty(mPicDesc)){
            //图片描述为空
            tvPicDesc.setVisibility(View.GONE);
        }
        else{
            mPicDescs=mPicDesc.split("\\|");//获得图片描述
            if(mPicDescs!=null){
                tvPicDesc.setVisibility(View.VISIBLE);
                tvPicDesc.setText(mPicDescs[0]);
            }
        }

        if (TextUtils.isEmpty(picNewsBean.getData().get(0).getPath())) {
            viewpager.setVisibility(View.GONE);
        } else {
            viewpager.setVisibility(View.VISIBLE);
            setPic(picNewsBean);
        }
    }


    public void dealData2(String content) {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(content)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (content.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        Gson gson = new Gson();
        PicNewsBean picNewsBean = gson.fromJson(content, PicNewsBean.class);
        tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL,picNewsBean.getData().get(0).getContent(),"text/html","UTF-8",null);
      //  tvDetailContent.setText(Html.fromHtml(picNewsBean.getData().get(0).getContent()));
        if (TextUtils.isEmpty(picNewsBean.getData().get(0).getPath())) {
            viewpager.setVisibility(View.GONE);
        } else {
            setPic(picNewsBean);
        }

    }

    private void setPic(PicNewsBean pic) {
        String[] pics = pic.getData().get(0).getPath().split("\\|");//图片路径
        for (int i = 0; i < pics.length; i++) {
            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) LayoutInflater.from(this).inflate(R.layout.item_adver, null);
            CommonUtil.loadPic(Uri.parse(Contacts.BASE_PIC_URL + pics[i]), simpleDraweeView);
            draweeViews.add(simpleDraweeView);
        }
        imageAdapter.notifyDataSetChanged();
        startPlay();
    }
    private void setPic2(String picPath) {


            SimpleDraweeView simpleDraweeView = (SimpleDraweeView) LayoutInflater.from(this).inflate(R.layout.item_adver, null);
            CommonUtil.loadPic(Uri.parse(Contacts.BASE_PIC_URL + picPath), simpleDraweeView);
            draweeViews.add(simpleDraweeView);

        imageAdapter.notifyDataSetChanged();

    }

    /**
     * 开始轮播图切换
     */
    private void startPlay() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    private void stopPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }

    @Override
    protected void onDestroy() {
        stopPlay();
        super.onDestroy();
    }

    class PicNewsAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewsDetailPicActivity.this, "加载中...",
                    "请稍后...", true, false);
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetContentAndPathXMLPhase.createParam(NewsDetailPicActivity.this, params[0]),
                    new GetContentAndPathXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class TopicAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewsDetailPicActivity.this, "加载中...",
                    "请稍后...", true, false);
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    TopicContentXMLPhase.createParam(NewsDetailPicActivity.this, params[0]),
                    new TopicContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    class SpecialAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewsDetailPicActivity.this, "加载中...",
                    "请稍后...", true, false);
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    SpecialContentXMLPhase.createParam(NewsDetailPicActivity.this, params[0]),
                    new SpecialContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            dealData(str);
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     *
     * @author caizhiming
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    break;
                case 0:
                    // 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewpager.getCurrentItem() == viewpager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        viewpager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewpager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewpager.setCurrentItem(viewpager.getAdapter().getCount() - 1);
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            currentItem = pos;
            try{
                if(!TextUtils.isEmpty(mPicDesc)){
                    if(!TextUtils.isEmpty(mPicDescs[pos])){
                        tvPicDesc.setVisibility(View.VISIBLE);
                        tvPicDesc.setText(mPicDescs[pos]);
                    }
                    else {
                        tvPicDesc.setVisibility(View.GONE);
                    }
                }
            }catch (IndexOutOfBoundsException e){
                tvPicDesc.setVisibility(View.GONE);
            }


        }

    }

    /**
     * 执行轮播图切换任务
     *
     * @author caizhiming
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
// TODO Auto-generated method stub
            synchronized (viewpager) {
                currentItem = (currentItem + 1) % draweeViews.size();
                handler.obtainMessage(2).sendToTarget();
            }
        }
    }

    class OnLineJudgeAsyncTask extends AsyncTask<String,Void,String>{


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewsDetailPicActivity.this, "加载中...",
                    "请稍后...", true, false);
        }

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    OnlineJudgeContentXMLPhase.createParam(NewsDetailPicActivity.this, params[0]),
                    new OnlineJudgeContentXMLPhase());
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            dealOnlineJudge(s);
        }
    }

    private void dealOnlineJudge(String result) {
        progressDialog.dismiss();
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("出错了，请重试");
            return;
        }

        JSONObject jsonObject= null;
        try {
            jsonObject = new JSONObject(result);
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            String picPath="";
            String content="";
            for(int i=0;i<jsonArray.length();i++){
                jsonObject=jsonArray.getJSONObject(i);
                picPath=jsonObject.getString("picPath");
                content=jsonObject.getString("content");
            }
            if(!TextUtils.isEmpty(picPath)){
                viewpager.setVisibility(View.VISIBLE);
                setPic2(picPath);
            }
            tvDetailContent.loadDataWithBaseURL(Contacts.BASE_URL,content,"text/html","UTF-8",null);
          //  tvDetailContent.setText(Html.fromHtml(content));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
